define(['jquery', 'api', 'user', 'util', 'text!pages/order/index.html', 'Vue', 'pages/index/goodsModel'], function($, api, user, util, tpl, Vue, goodsModel) {
    var $loginForm,
        vm,
        timer,
        goodsTimer,
        reloadTime = 1000,
        ORDER_STATUS = { '49': '未成交', '50': '已成交', '51': '已撤单', '54': '部分撤单', '55': '部分成交' };
    var controller = {
        init: function() {
            var that = this;
            if (!user.checkLogin()) return;
            api.setTitle(L('html_title_order'));
            api.headerShow(0);
            api.footerShow(1); //显示底部导航
            api.initFooter('order');


            this.render(function() {
                that.loadHoldOrders();
            });

        },
        render: function(cb) {
            var that = this;
            $('#common').html('<div id="orderCt"></div>');

            vm = new Vue({
                el: '#orderCt',
                data: {
                    userFund: {},
                    show: true,
                    loading: false,
                    nav: 1,
                    totalNetworth: 0, //总市值
                    totalPl: 0, //总盈亏
                    totalRiskrate: 0, //总盈亏比
                    code2goods: {},
                    codeToflashsale: {},
                    holdOrders: [],
                    ltOrders: [],
                    showBtnOrder: false,
                    pop: false, //挂单表单显示：false隐藏，true显示
                    cancelOrderFormSwitch: false, //撤单表单显示：false隐藏，true显示
                    code2mindecimal: {}, //{goodscode：mindecimal}
                    code2order: {}, //{goodscode：order}
                    formTitle: '',
                    code2hqprice: {}, //行情价 {goodscode:price}
                    userCountHash: {}, //用户总持仓查询
                    code2Hq: {}, //商品对应的行情
                    priceOptionType: '', //涨跌停价格单选按钮,up为涨停、down为跌停
                    upPrice: 0, //涨停价
                    downPrice: 0, //跌停价
                    formPrice: 0, //挂单价格
                    formNum: 1, //购买数量
                    formCount: 0, //购买总计
                    formIsFlashsale: false, //是否正在抢购
                    form: {
                        ordersn: '',
                        goodsname: '',
                        goodscode: '',
                        canamount: 0, //可买数
                        mindecimal: 0,
                        type: 1, //1认购,2挂单
                        direct: 98 //买入，2卖出
                    },
                    hasRange: true
                },
                watch: {
                    formPrice: function(now, old) { // 监控挂单价格输入
                        if (isNaN(now) || parseFloat(now) <= 0) {
                            this.formPrice = 1;
                        } else {
                            this.formPrice = this.formPrice;
                        }
                        if (now != vm.upPrice && now != vm.downPrice) {
                            vm.priceOptionType = '';
                        }
                        // 总计
                        this.formCountFunc(this.formPrice, this.formNum);
                    },
                    formNum: function(now, old) { // 监控挂单价格输入
                        if (!isNaN(now) || parseInt(now) > 0 || now == '') {
                            this.formNum = now ? parseInt(now) : '';
                        } else {
                            this.formNum = '';
                        }
                        this.formCountFunc(this.formPrice, this.formNum);
                    }

                },
                computed: {
                    // 涨停价
                    computedUpPrice: function() {
                        delete this.code2Hq[this.form.goodscode];
                        if (typeof this.code2Hq[this.form.goodscode] == 'undefined') {
                            var settl = parseInt(this.code2goods[this.form.goodscode].issueprice);
                        } else {
                            var settl = parseFloat(util.priceFormat(vm.form.mindecimal, this.code2Hq[this.form.goodscode].yessettl));
                        }

                        var
                            updownupperlimit = parseFloat(this.code2goods[this.form.goodscode].updownupperlimit),
                            v = settl + updownupperlimit / 100 * settl;
                        var updowntype = this.code2goods[this.form.goodscode].updowntype; //交易手续费类型:49比例，50固定,51不设涨停板

                        if (updowntype == 49) { //比例
                            v = v.toFixed(vm.form.mindecimal);
                        } else if (updowntype == 50) { //固定
                            v = (settl + updownupperlimit).toFixed(vm.form.mindecimal); //涨停
                        } else if (updowntype == 51) { //不设涨停板 3-51
                            //不显示价格区间
                            this.hasRange = true;
                        }

                        this.upPrice = v;
                        return v;
                    },
                    // 跌停价
                    computedDownPrice: function() {
                        if (typeof this.code2Hq[this.form.goodscode] == 'undefined') {
                            var settl = parseInt(this.code2goods[this.form.goodscode].issueprice);
                        } else {
                            var settl = parseFloat(util.priceFormat(vm.form.mindecimal, this.code2Hq[this.form.goodscode].yessettl));
                        }
                        // yessettl 昨日结算价格，updownlowerlimit 涨跌幅下线，updownlowerlimit 涨跌幅上线
                        var
                            updownlowerlimit = this.code2goods[this.form.goodscode].updownlowerlimit,
                            v = settl - updownlowerlimit / 100 * settl;
                        //是固定类型就用行情价

                        var updowntype = this.code2goods[this.form.goodscode].updowntype; //交易手续费类型:49比例，50固定,51不设涨停板

                        if (updowntype == 49) { //比例 1-49
                            v = v.toFixed(vm.form.mindecimal);
                        } else if (updowntype == 50) { //固定 2-50
                            v = (settl - updownlowerlimit).toFixed(vm.form.mindecimal); //跌停
                        } else if (updowntype == 51) { //不设涨停板 3-51
                            //不显示价格区间
                            this.hasRange = true;
                        }



                        this.downPrice = v; //跌停价
                        return v;
                    },
                    formTitlePrice: function() {
                        var str = [];
                        if (this.form.type == 1) {
                            if (this.form.direct == 98) {
                                if (this.formIsFlashsale) {
                                    str.push('抢购价格');
                                } else {
                                    str.push('买入价格');
                                }
                            } else if (this.form.direct == 115) {
                                str.push('卖出价格');
                            }
                        } else if (this.form.type == 2) {
                            str.push('挂单价格');
                        }
                        return str.join('');
                    },
                    formTitleNum: function() {
                        var str = [];
                        if (this.form.type == 1) {
                            if (this.formIsFlashsale) {
                                str.push('抢购数量');
                            } else {
                                str.push('认购数量');
                            }
                        } else if (this.form.type == 2) {
                            str.push('挂单数量');
                        }
                        return str.join('');
                    },
                    formTitleNumMax: function() {
                        var str = [];
                        if (this.form.type == 1) {
                            if (this.formIsFlashsale) {
                                str.push('可抢数量');
                            } else if (this.form.direct == 98) {
                                str.push('可买数量');
                            } else if (this.form.direct == 115) {
                                str.push('可卖数量');
                            }
                        } else if (this.form.type == 2) {
                            str.push('可挂数量');
                        }
                        return str.join('');
                    },
                    formTitlePriceTotal: function() {
                        var str = [];
                        if (this.form.type == 1) {
                            if (this.formIsFlashsale) {
                                str.push('抢购金额');
                            } else {
                                str.push('认购金额');
                            }
                        } else if (this.form.type == 2) {
                            str.push('挂单金额');
                        }
                        return str.join('');
                    },
                },
                filters: {
                    direct: function(v) {
                        if (v == 98) return '买入';
                        if (v == 115) return '卖出';
                    },
                    holdNum: function(order) {
                        return parseInt(order.holdamount) + parseInt(order.limitamount) + parseInt(order.freezeamount);
                    },
                    status: function(v) {
                        return ORDER_STATUS[v] ? ORDER_STATUS[v] : '';
                    },
                    price: function(s, mindecimal) {
                        return s ? util.priceFormat(mindecimal, s) : '0.00';
                    },
                    toFixed: function(v) {
                        return !isNaN(v) ? v.toFixed(2) : '0.00';
                    },
                    timeFmt: function(v) {
                        var arr = [];
                        // "2017-03-07 21:03:42"=>["2017-03-07", "21:03:42"]
                        if (typeof v == 'string') {
                            arr = v.split(' ');
                        }
                        return arr[1] ? arr[1] : (arr[0] ? arr[0] : '');
                    },
                    priceFormat: function(v, mindecimal) {
                        return v ? util.priceFormat(mindecimal, v) : '';
                    },
                    titleFormat: function(v) {
                        return util.subString(v, 35, 1);
                    },
                    pl: function(v) {
                        var prefix = '';
                        if (!isNaN(v)) {
                            if (v > 0) {
                                prefix = '+';
                            }
                            return prefix + v;
                        } else {
                            return '-'
                        }
                    },
                    rate: function(v) {
                        var prefix = '';
                        if (!isNaN(v)) {
                            if (v > 0) {
                                prefix = '+';
                            }
                            return prefix + v + '%';
                        } else {
                            return '0'
                        }
                    }
                },
                methods: {
                    resetForm: function() {
                        this.form = {
                            canamount: 0,
                            ordersn: '',
                            goodsname: '',
                            goodscode: '',
                            mindecimal: 0,
                            type: 1, //2挂单,1认购
                            direct: 98 //买入，2卖出
                        };
                        this.priceOptionType = ''; //涨跌停价格单选按钮,up为涨停、down为跌停
                        this.upPrice = 0; //涨停价
                        this.downPrice = 0; //跌停价
                        this.formPrice = 0; //挂单价格
                        this.formNum = 1; //购买数量
                        this.formCount = 0; //购买总计
                    },
                    formCountFunc: function(price, num) { //计算购买总额
                        if (this.form.type == 1) {
                            this.formCount = util.priceFormat(vm.form.mindecimal, price * num);
                        } else {
                            this.formCount = util.priceFormat(0, price * num);
                        }
                    },
                    priceOption: function(opt) { //挂单涨跌停价格选择
                        vm.priceOptionType = opt;
                        if (opt == 'up') {
                            vm.formPrice = vm.upPrice;
                        } else if (opt == 'down') {
                            vm.formPrice = vm.downPrice;
                        }
                    },
                    //            		setSlCanamount:function(goods){//可认购数量计算
                    //	              		/*客户可认购数量=min（
                    //	              		 * 该会员配额下的剩余数量，
                    //	              		 * 该商品剩余数量 goods.surplus，
                    //	              		 * 该客户最大认购数量 maxperamount-该客户已认购数量，
                    //	              		 * 该客户可用资金可以认购的数量(userFund.balance/issueprice)
                    //	              		 * ）*/
                    //	              		var userNum = parseFloat(util.priceFormat(2,this.userFund.balance))/parseFloat(util.priceFormat(goods.mindecimal, goods.issueprice));
                    //	              		this.form.canamount = Math.min(goods.surplus,goods.maxperamount,userNum);
                    //            		},
                    // 买入卖出表单头
                    setFormTitle: function(code, direct, issuestatus) {
                        var str = [];

                        if (issuestatus == 50 || issuestatus == 55) {
                            // 是否是抢购
                            if (this.formIsFlashsale) {
                                str.push('立即抢购');
                            } else {
                                str.push('立即认购');
                            }
                        } else {
                            if (direct == 98) {
                                str.push('买入');
                            } else if (direct == 115) {
                                str.push('卖出');
                            }
                            str.push('挂单');
                        }


                        this.formTitle = str.join('');
                    },
                    tabChange: function(i) { //切换类型，1持仓， 2挂单
                        if (i == 1) that.loadHoldOrders();
                        else if (i == 2) that.loadLtOrders();
                        //            			if(this.nav!=i && i==1) that.loadHoldOrders();
                        //            			else if(this.nav!=i && i==2) that.loadLtOrders();
                        this.nav = i;
                        this.pop = false;
                        this.cancelOrderFormSwitch = false;
                    },
                    showTable: function(order) { //表格显示隐藏
                        this.showBtnOrder = this.showBtnOrder == order ? false : order;
                    },
                    hq: function(order) { //行情

                        if (this.nav == 2) {
                            location.hash = ['#/index/producttrade/', order.goodscode].join('');
                        } else {
                            switch (order.issuestatus) {
                                //挂单
                                case '53':
                                    location.hash = ['#/index/producttrade/', order.goodscode].join('');
                                    break;
                                default:
                                    util.msg('流通期才可操作');

                            }

                        }
                    },
                    showForm: function(direct, order) { //买入卖出表单显示
                        if (typeof this.code2goods[order.goodscode].issuestatus == 'undefined') return;
                        var goods = this.code2goods[order.goodscode],
                            issuestatus = goods.issuestatus,
                            mindecimal = goods.mindecimal,
                            issueprice = goods.issueprice;
                        //  	        		this.form.canamount=0; //可买数量重置

                        // 认购、认购结束不能卖出
                        if ((issuestatus == 50 || issuestatus == 55)) {
                            this.form.type = 1; //认购

                            // 当前用户认购/抢购最新购买信息
                            that.loadSlGoodsCount(order.goodscode, function(data) {
                                // 是否抢购进行中
                                vm.formIsFlashsale = data.status === '1' ? true : false;
                                vm.goods = vm.code2goods[order.goodscode];
                                // 可买数量
                                vm.form.canamount = parseInt(data.canpurchaseamount);
                                // 价格
                                vm.formPrice = util.priceFormat(data.mindecimal, data.issueprice);
                                // 是否正在抢购
                                vm.setFormTitle(order.goodscode, direct, issuestatus);
                            });
                            //  	        			this.setSlCanamount(goods); // 可订购数
                        } else {
                            this.form.type = 2; //挂单
                            //挂单价格默认值是行情价
                            this.formPrice = util.priceFormat(order.mindecimal, vm.code2hqprice[goods.goodscode]);

                            if (direct == 98) {
                                // 可挂买数量
                                that.ltGoodsNewest(goods.goodscode, 'b');
                                //	    	        			this.form.canamount =  util.getCanamount({
                                //	    	        				direct: direct,
                                //	    	        				goods: goods,
                                //	    	        				hqprice: vm.code2hqprice[goods.goodscode],
                                //	    	        				holdamount: this.userCountHash[goods.goodscode].holdamount,
                                //	    	        				balance: vm.userFund.balance,
                                //	    	        				inprice: this.formPrice
                                //	    	        			});
                            } else if (direct == 115) {
                                that.ltGoodsNewest(goods.goodscode, 's');
                                // 可挂卖数量，=当前商品持仓的可用数量 
                                //            					this.form.canamount = parseInt(order.allowsellamount);
                            }

                        }
                        // 不能卖出（除了 流通期）
                        if (direct == 115 && (issuestatus != 53)) {
                            util.msg('流通期才可操作');
                            return;
                        }
                        //能买入（除了认购期、流通期）
                        if (direct == 98 && (issuestatus != 50 && issuestatus != 53)) {
                            util.msg('流通期才可操作');
                            return;
                        }

                        this.setFormTitle(order.goodscode, direct, issuestatus);
                        this.form.ordersn = order.ordersn;
                        this.form.goodscode = order.goodscode;
                        this.form.goodsname = order.goodsname;
                        this.form.direct = direct; //买98，115卖
                        this.form.mindecimal = order.mindecimal;
                        this.formNum = order.orderamount ? order.orderamount : 1; //挂单数量
                        this.pop = true; //买卖表单显示
                        this.cancelOrderFormSwitch = false; //撤单表单隐藏
                    },
                    showFormSubmit: function() { //挂单买入卖出表单提交
                        this.pop = true;

                        if (this.form.type == 1) { //认购、抢购

                            if (vm.formNum > this.form.canamount || this.canamount == 0) {
                                util.msg('可购数量不足');
                                return;
                            }

                            if (this.form.direct === 98) { //买入
                                if (this.formIsFlashsale) {
                                    //执行抢购
                                    that.flashsaleSub(this.codeToflashsale[this.form.goodscode].flashsale.saleid, this.form.goodscode, vm.formNum);
                                } else {
                                    that.createSlOrder(this.form.goodscode, vm.formNum);
                                }

                            }
                        } else if (this.form.type == 2) { // 挂单买入卖出

                            if (this.form.direct == 98) {
                                that.ltbuy();
                            } else if (this.form.direct == 115) { //卖出
                                that.ltsell();
                            }
                        }
                    },
                    hideForm: function() {
                        this.pop = false;
                    },
                    cancelOrderFormShow: function(order) { //撤单确认
                        // 未成交、部分成交才可以撤单
                        if (order.orderstatus == 49 || order.orderstatus == 55) {
                            this.form.ordersn = order.ordersn;
                            this.form.goodsname = order.goodsname;
                            this.form.goodscode = order.goodscode;
                            this.formPrice = parseFloat(util.priceFormat(order.mindecimal, order.orderprice)); //挂单价格
                            this.formNum = parseInt(order.orderamount); //挂单数量
                            this.form.totalprice = parseFloat(util.priceFormat(order.mindecimal, order.orderprice * order.orderamount)); //挂单数量
                            this.cancelOrderFormSwitch = true;
                            this.pop = false;
                        } else {
                            util.msg('状态为未成交、部分成交才可撤单');
                        }
                    },
                    cancelOrderFormHide: function() { //撤单确认-隐藏
                        this.cancelOrderFormSwitch = false;
                    },
                    killOrderFormSubmit: function() { //撤单表单
                        var that = this,
                            cb = function() {
                                vm.hideForm();
                                vm.resetForm();
                                vm.cancelOrderFormSwitch = false;
                                setTimeout(function() { vm.reload() }, reloadTime);
                            };
                        api.cancelLtOrder({ ordersn: this.form.ordersn }, function(rs) {
                            if (rs.retcode == '0') {
                                util.msg('撤单成功');
                                cb();
                            } else {
                                util.dealErrorCode(rs.retcode);
                            }
                        });
                    },
                    reload: function() {
                        if (vm.nav == 1) {
                            that.loadHoldOrders();
                        } else if (vm.nav == 2) {
                            that.loadLtOrders();
                        }
                    },
                    //提货
                    pickup: function(order) {
                        if (order.issuestatus == goodsModel.status_ltq) {
                            location.hash = '#/order/pickup/' + order.goodscode;
                        } else {
                            util.msg('流通期才能提货');
                        }
                    }
                },
                template: tpl
            });

            typeof cb == 'function' && cb();
        },
        ltGoodsNewest: function(code, direct) { //挂单买入卖出可挂数量
            //direct=b b 挂单买入 s 挂单卖出
            api.ltGoodsNewest({ goodscode: code, direct: direct }, function(rs) {
                if (rs.retcode === '0' && rs.data) {
                    vm.form.canamount = parseInt(rs.data.canpurchaseamount);
                    //      			this.form.canamount = parseInt(this.form.canamount);
                }
            });
        },
        createSlOrder: function(code, num) {
            var that = this,
                cb = function() {
                    vm.hideForm();
                    vm.resetForm();
                    setTimeout(function() { vm.reload() }, reloadTime);
                };

            if (this.isValid()) {
                api.createSlOrder({ goodscode: code, amount: num },
                    function(rs) {
                        if (rs.retcode == 0) {
                            util.msg('认购成功！');
                            cb();
                        } else if (rs.retcode !== '0') {
                            util.dealErrorCode(rs.retcode);
                        }
                    }
                );
            }
        },
        flashsaleSub: function(saleid, code, num) { //抢购提交
            var that = this,
                cb = function() {
                    vm.hideForm();
                    vm.resetForm();
                    setTimeout(function() { vm.reload() }, reloadTime);
                };
            // 检查数量限制
            if (isNaN(num) || num == '' || num <= 0) {
                util.msg('购买数量不能小于0');
                return;
            }
            //      	console.log(vm.goods);return;////
            if (num < vm.goods.flashsale.minpurchase) {
                util.msg('最小购买数量不能小于' + vm.goods.flashsale.minpurchase);
                return;
            }
            if (num > vm.goods.flashsale.maxpurchase) {
                util.msg('最大购买数量不能大于' + vm.goods.flashsale.maxpurchase);
                return;
            }
            // isrepurchaseable 可重复抢购:'1' - 允许;'2' - 不允许
            // purchaseamount 已抢购数量

            api.flashsale({ saleid: saleid, goodscode: code, purchasenum: num }, function(rs) {
                if (rs.retcode === '0') {
                    util.msg('抢购成功！');
                    cb();
                } else {
                    util.dealErrorCode(rs.retcode);
                }
            });
        },
        ltbuy: function() { //挂单买入
            if (this.isValid(vm.form)) {
                var that = this,
                    cb = function() {
                        vm.hideForm();
                        vm.resetForm();
                        setTimeout(function() { vm.reload() }, reloadTime);
                    };

                api.createLtOrder({ goodscode: vm.form.goodscode, orderamount: vm.formNum, orderprice: vm.formPrice * Math.pow(10, vm.form.mindecimal) },
                    function(rs) {
                        if (rs.retcode == '0') {
                            util.msg('买入挂单成功');
                            cb();
                        } else if (rs.retcode !== '0') {
                            util.dealErrorCode(rs.retcode);
                        }
                    }
                );
            }
        },
        ltsell: function() { //挂单卖出
            if (this.isValid(vm.form)) {
                var that = this,
                    cb = function() {
                        vm.hideForm();
                        vm.resetForm();
                        setTimeout(function() { vm.reload() }, reloadTime);
                    };
                api.sellLtOrder({ goodscode: vm.form.goodscode, orderamount: vm.formNum, orderprice: vm.formPrice * Math.pow(10, vm.form.mindecimal) },
                    function(rs) {
                        if (rs.retcode == '0') {
                            util.msg('卖出挂单成功');
                            cb();
                        } else if (rs.retcode !== '0') {
                            util.dealErrorCode(rs.retcode);
                        }
                    }
                );
            }
        },
        isValid: function(data) { //表单验证
            var error = false,
                errorHash = {
                    //		           	price:'请填写价格！',
                    //					count:'请填写数量！'
                };
            for (var key in errorHash) {
                if (data[key] == '') {
                    error = errorHash[key];
                    break;
                }
            }

            if (isNaN(vm.formPrice) || vm.formPrice == '' || vm.formPrice <= 0) {
                error = '填写价格必须大于0';
            }
            if (isNaN(vm.formNum) || vm.formNum == '' || vm.formNum <= 0) {
                error = '填写数量必须大于0';
            }
            if (isNaN(vm.form.canamount) || vm.form.canamount <= 0 || vm.formNum > vm.form.canamount) {
                if (vm.form.type) {
                    error = '可挂数量必须大于0';
                } else {
                    error = '可购数量必须大于0';
                }
            }

            if (error) {
                util.msg(error);
                return false;
            } else {
                return true;
            }
        },
        queryGoodHold: function() {
            api.queryGoodHold({}, function(rs) { // 持仓汇总
                if (rs.retcode === '0' && rs.data) {
                    rs.data.map(function(item) {
                        vm.userCountHash[item.goodscode] = item;
                    });
                }
            });
        },
        loadHoldOrders: function() { // 持仓单
            var that = this,
                goodscodeAll = [],
                cb = function() {
                    vm.holdOrders.map(function(item) {
                        vm.code2order[item.goodscode] = item;
                        goodscodeAll.push(item.goodscode);
                    });

                    that.loadUserFund();
                    that.loadGoodsInfo(goodscodeAll.join(','));
                    that.queryGoodHold();
                };
            vm.loading = true;
            api.holdOrders({
                //	    	    begindate:new Date().format('yyyy-M-d'),
                //	    	    enddate:new Date().format('yyyy-M-d')
            }, function(rs) {
                vm.loading = false;
                if (rs.retcode == '0') {
                    vm.holdOrderShow = true;
                    if (rs.data) {
                        vm.holdOrders = rs.data;
                        cb();
                    }
                } else {
                    util.dealErrorCode(rs.retcode);
                }
            });
        },
        loadLtOrders: function() { //挂单
            var that = this;
            var items = [];
            vm.loading = true;

            api.ltOrders({
                begindate: new Date().format('yyyy-M-d'),
                enddate: new Date().format('yyyy-M-d')
            }, function(rs) {
                vm.loading = false;
                if (rs.retcode == '0') {
                    if (rs.data) {
                        vm.ltOrders = rs.data;
                        vm.ltOrders.map(function(item) {
                            vm.code2order[item.goodscode] = item;
                        });
                    }
                } else {
                    util.dealErrorCode(rs.retcode);
                }
            });
        },
        loadGoodsInfo: function(goodscode) {
            var that = this,
                cb = function() {
                    that.clearTmer();
                    setTimeout(that.timer(), 0) //行情
                };
            vm.loading = true;

            api.goodsInfo({
                data: { goodscode: goodscode },
                success: function(rs) {
                    vm.loading = false;

                    if (rs.retcode == '0') {
                        //处理商品数据
                        goodsModel.addGoods(rs.data);
                        vm.code2goods = goodsModel.codeToGoods;
                        vm.codeToflashsale = goodsModel.codeToFlashsale; //拿到进行的抢购商品

                        cb();
                    } else {
                        if (goodsTimer) clearTimeout(goodsTimer);
                        goodsTimer = setTimeout(cb, 1000);
                    }
                },
                error: function(xhr, status) {
                    if (goodsTimer) clearTimeout(goodsTimer);
                    goodsTimer = setTimeout(cb, 1000);
                }
            });
        },
        loadSlGoodsCount: function(goodscode, callback) { //我要认购是的参数 canpurchaseamount 可认购数量
            var that = this,
                cb = function() {
                    that.loadSlGoodsCount();
                };
            api.slgoodsCount({ goodscode: goodscode }, function(rs) {
                if (rs.retcode === '0' && rs.data) {
                    typeof callback === 'function' && callback(rs.data);
                } else {
                    setTimeout(cb, 1000);
                }
            });
        },
        timer: function() {
            var that = this,
                cb = function() { that.timer(); };
            api.quotations({ goodscode: Object.keys(vm.code2goods).join(',') }, // 不用code2order的原因是以实际取到商品为准
                function(rs) {
                    if (rs.retcode === '0' && rs.data) {
                        that.refreshHq.call(that, rs.data);
                        if (vm.show) {
                            that.clearTmer();
                            timer = setTimeout(cb, util.cfg.refreshTime);
                        }
                    }
                },
                function(xhr, status) {
                    timer = setTimeout(cb, util.cfg.refreshTime);
                }
            )
        },
        refreshHq: function(goodsHqAll) {
            var
                fpl = 0, // 盈亏
                rate = 0, // 盈亏比
                totalNetworth = 0, //总市值
                totalPl = 0, //总市值
                totalRiskrate = 0; //总市值

            for (i in goodsHqAll) {
                if (typeof goodsHqAll[i].slsymbol == 'undefined') continue;
                vm.code2Hq[goodsHqAll[i].slsymbol.goodscode] = goodsHqAll[i]; //按商品记录行情

                var code = goodsHqAll[i].slsymbol.goodscode, // 商品代码
                    agreeunit = vm.code2goods[code].agreeunit, // 商品合约单位
                    issuestatus = vm.code2goods[code].issuestatus, // 商品状态
                    order = vm.code2order[code], // 商品码对应的订单
                    holdprice = !isNaN(order.holdprice) ? order.holdprice : 0, //持仓价
                    mindecimal = !isNaN(order.mindecimal) ? parseInt(order.mindecimal) : 0, // 订单商品小数位
                    issueprice = vm.code2goods[code].issueprice, // 现价    
                    // 总持仓=持仓数量+受限数量+冻结数量
                    holdamount = !isNaN((+order.holdamount) + (+order.limitamount) + (+order.freezeamount)) ? (+order.holdamount) + (+order.limitamount) + (+order.freezeamount) : 0, // 订单持仓数
                    price = !isNaN(goodsHqAll[i].price) ? goodsHqAll[i].price : 0; // 现价

                // 行情渲染
                var $hqfpl = $("#hqfpl" + code);
                var $rate = $("#hqrate" + code);

                //上市的商品，需要行情
                if (issuestatus === '53') {
                    price = price == 0 && !isNaN(goodsHqAll[i].yesclose) ? goodsHqAll[i].yesclose : price; // 昨收价
                    price = price == 0 ? issueprice : price; // 没上市取发行价格
                    $("#hqprice" + code).html(util.priceFormat(mindecimal, price)); //现价
                    //总市值
                    totalNetworth += holdamount * (price / Math.pow(10, mindecimal)); //一个订单市值
                } else {
                    // 没上市取发行价格
                    price = issueprice;
                    $("#hqprice" + code).html(util.priceFormat(mindecimal, issueprice)); //现价    	
                    //总市值
                    totalNetworth += holdamount * (issueprice / Math.pow(10, mindecimal)); //一个订单市值

                }


                // 没有现价会出现负数
                if (price > 0) {
                    fpl = util.fpl(mindecimal, price, holdprice, holdamount, agreeunit);
                    rate = holdprice > 0 && holdamount > 0 ? ((price - holdprice) / holdprice * 100).toFixed(2) : '0.00';

                    if (fpl > 0) {
                        $hqfpl.removeClass('color-down');
                        $hqfpl.addClass('color-up');
                        $rate.removeClass('color-down');
                        $rate.addClass('color-up');
                    } else {
                        $hqfpl.removeClass('color-up');
                        $hqfpl.addClass('color-down');
                        $rate.removeClass('color-up');
                        $rate.addClass('color-down');
                    }
                    totalPl += fpl; //一个订单盈亏
                    // 订单盈亏
                    $hqfpl.html(fpl.toFixed(2));
                    $rate.html(rate + '%');
                }

                // 行情价
                vm.code2hqprice[code] = price;
            }

            if (!isNaN(totalNetworth) && totalNetworth > 0) {
                // 总市值=∑单个商品总持仓*当前行情价格  
                vm.totalNetworth = totalNetworth.toFixed(2);
                // 总盈亏=总市值-∑单个商品总持仓*持仓均价
                vm.totalPl = totalPl.toFixed(2);
                // 总盈亏比例= 总盈亏 /（总市值-总盈亏）
                vm.totalRiskrate = (totalPl / (totalNetworth - totalPl) * 100).toFixed(2);
            }
        },
        loadUserFund: function() {
            api.userInfo(function(rs) {
                if (rs.retcode == '0') {
                    vm.userFund = rs.data;
                } else {
                    util.msg('用户信息获取失败！');
                }
            });
        },
        clearTmer: function() {
            if (timer) clearTimeout(timer);
        },
        onRouteChange: function() {
            if (vm) {
                vm.nav = 1;
                vm.show = false;
            }
            this.clearTmer();
        }
    }
    return controller;
})